<template>
  <div style="margin-top: 2vh">
    <div style="background-color: white; width: 68vw; margin: auto;">
      <!-- 上方标题 -->
      <div style="border-bottom: 1px solid #e9e9e9; height: 7vh; width: 100%;">
        <span style="font-weight: bold; font-size: 1.1rem; line-height: 7vh; margin-left: 1.5vw;">专利上传</span>
        <span style="font-size: 0.8rem; color: #8c8c8c; margin-left: 1vw; line-height: 7vh;">请上传您获得的专利证书。</span>

      </div>

      <pdf-preview
          ref="pdfPreviewRef"
          @update:pdf-path="updatePdfPath"
          @rotations-changed="handleRotationsChanged"
      ></pdf-preview>
    </div>

    <!-- 填写信息 -->
    <div style="background-color: white; width: 68vw; margin: auto; display: flex; flex-direction: column; padding-bottom: 5vh; margin-top: 3vh;margin-bottom: 3vh">
      <div style="flex: 1;">
        <div style="border-bottom: 1px solid #e9e9e9; height: 7vh;">
          <span style="font-weight: bold; font-size: 1.1rem; line-height: 7vh; margin-left: 1.5vw">填写信息</span>
        </div>
        <div>
          <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px" style="margin-top: 5vh">
            <el-form-item label="专利名称" prop="title" required>
              <el-input placeholder="请填写专利名称" v-model="ruleForm.title" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="专利类型" prop="patentType" required>
              <el-radio-group v-model="ruleForm.patentType">
                <el-radio label="发明">发明</el-radio>
                <el-radio label="实用新型">实用新型</el-radio>
                <el-radio label="外观设计">外观设计</el-radio>
                <el-radio label="国际专利">国际专利</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="专利状态" prop="patentStatus" required>
              <el-radio-group v-model="ruleForm.patentStatus">
                <el-radio label="已授权">已授权</el-radio>
                <el-radio label="已受理">已受理</el-radio>
                <el-radio label="已申请">已申请</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="专利编号" prop="patentNumber" >
              <el-input placeholder="如: xx" v-model="ruleForm.patentNumber" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="专利权人" prop="patentOwner">
              <el-input placeholder="请输入专利权人" v-model="ruleForm.patentOwner" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="授权公告日" prop="authorizationDate">
              <el-date-picker
                  v-model="ruleForm.authorizationDate"
                  type="date"
                  placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="申请编号" prop="applicationNumber">
              <el-input placeholder="请输入申请编号" v-model="ruleForm.applicationNumber" style="width: 34vw;"></el-input>
            </el-form-item>
            <el-form-item label="专利申请日" prop="applicationDate">
              <el-date-picker
                  v-model="ruleForm.applicationDate"
                  type="date"
                  placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="本人排名" prop="authorRank" required>
              <el-select v-model="ruleForm.authorRank" style="width: 34vw;">
                <el-option v-for="i in 13" :key="i" :label="i.toString()" :value="i"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否同步" prop="syncStatus">
              <el-select v-model="ruleForm.syncStatus" style="width: 34vw;" placeholder="请选择是否同步">
                <el-option label="是" :value="'是'"></el-option>
                <el-option label="否" :value="'否'"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="关联课题" prop="projectId">
              <el-select v-model="ruleForm.projectId" placeholder="请选择本成果所属课题" style="width: 34vw;">
                <el-option
                    v-for="project in longitudinalProjects"
                    :key="project.id"
                    :label="project.projectName"
                    :value="project.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="作者信息" prop="authorInfo" required>
              <div style="background-color: #f9f9f9; width: 55vw; height: auto; padding: 10px; border-radius: 4px;">
                <!-- 表头 -->
                <div style="display: flex; align-items: center; padding: 8px 0; border-bottom: 1px solid #e8e8e8;">
                  <div style="width: 60px; text-align: center;">排序</div>
                  <div style="width: 100px; margin-left: 10px;">中文名</div>
                  <div style="width: 100px; margin-left: 10px;">作者身份</div>
                  <div style="flex: 1; margin-left: 10px;">单位名称</div>
                  <div style="width: 80px; margin-left: 10px;">操作</div>
                </div>

                <!-- 作者列表 -->
                <div v-for="(author, index) in ruleForm.authorInfo" :key="index" style="display: flex; align-items: center; padding: 8px 0; border-bottom: 1px solid #f0f0f0;">
                  <el-select v-model="author.rank" style="width: 60px;">
                    <el-option
                        v-for="item in ruleForm.RankOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                  </el-select>

                  <el-input v-model="author.name" style="width: 100px; margin-left: 10px;"></el-input>

                  <el-select v-model="author.identity" style="width: 100px; margin-left: 10px;">
                    <el-option
                        v-for="item in ruleForm.ShipOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                  </el-select>

                  <el-select v-model="author.institution" placeholder="单位名称" style="flex: 1; margin-left: 10px;">
                    <el-option label="信息工程学院" value="信息工程学院"></el-option>
                  </el-select>


                  <el-button
                      type="danger"
                      size="small"
                      @click="removeAuthor(index)"
                      style="width: 80px; margin-left: 10px;">
                    删除
                  </el-button>
                </div>

                <el-button @click="addAuthor" style="margin-top: 10px;">添加共同作者</el-button>
              </div>
            </el-form-item>
            <el-form-item label="备注信息" prop="remarks">
              <el-input type="textarea" :rows="4" placeholder="请输入备注信息" v-model="ruleForm.remarks" style="width: 34vw;"></el-input>
            </el-form-item>
          </el-form>
          <div style="display: flex; justify-content: center; margin-top: 2vh">
            <button @click="submit" class="upload-button" style="width: 10vw;" :disabled="isSubmitting">
              {{ isSubmitting ? '上传中...' : '上 传' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { savePatent } from '@/api/Manage/patent.js';
import { getCompletedLongitudinal } from '@/api/Research/Longitudinal.js';
import PdfPreview from "@/components/PdfPreview.vue";
import { batchUpdatePdfPages } from "@/api/Manage/File.js";

const router = useRouter();
const ruleFormRef = ref(null);
const pdfPreviewRef = ref(null);
const longitudinalProjects = ref([]); // 存储课题列表
const isSubmitting = ref(false) // 提交状态
const hasRotations = ref(false) // 是否有旋转
const currentRotations = ref([]) // 存储当前的旋转信息

const ruleForm = reactive({
  title: '',
  patentType: '',
  patentStatus: '',
  syncStatus:"否",
  patentNumber: '',
  patentOwner: '',
  authorizationDate: '',
  applicationNumber: '',
  applicationDate: '',
  authorRank: null,
  projectId: null,
  pdfPath: '',
  remarks: '',
  authorInfo: [{
    rank: '1',
    name: '',
    identity: '老师',
    institution: ''
  }],
  RankOptions: [
    { value: '1', label: '1' },
    { value: '2', label: '2' },
    { value: '3', label: '3' },
    { value: '4', label: '4' },
    { value: '5', label: '5' },
    { value: '6', label: '6' },
    { value: '7', label: '7' },
    { value: '8', label: '8' },
    { value: '9', label: '9' },
    { value: '10', label: '10' },
    { value: '11', label: '11' },
    { value: '12', label: '12' },
    { value: '13', label: '13' },
  ],
  ShipOptions: [
    { value: '老师', label: '老师' },
    { value: '博士生', label: '博士生' },
    { value: '硕士生', label: '硕士生' },
    { value: '本科生', label: '本科生' },
    { value: '其他', label: '其他' }
  ]
});

const rules = {
  title: [
    { required: true, message: '请输入专利名称', trigger: 'blur' }
  ],
  patentType: [
    { required: true, message: '请选择专利类型', trigger: 'change' }
  ],
  patentStatus: [
    { required: true, message: '请选择专利状态', trigger: 'change' }
  ],
  authorRank: [
    { required: true, message: '请选择本人排名', trigger: 'change' }
  ],
  authorInfo: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请至少添加一位作者'))
        } else {
          // 检查每位作者的必填字段
          const hasInvalidAuthor = value.some(author =>
              !author.name || !author.identity || !author.institution || !author.rank
          )
          if (hasInvalidAuthor) {
            callback(new Error('请完善所有作者的信息'))
          } else {
            callback()
          }
        }
      },
      trigger: 'change'
    }
  ]
};

const formatDate = (date) => {
  if (!date) return '';
  const formattedDate = new Date(date).toISOString().split('T')[0];
  return formattedDate;
};

const updatePdfPath = (newPath) => {
  ruleForm.pdfPath = newPath.firstImageUrl
  console.log('PDF path updated:', newPath)
}

// 处理旋转状态变化
const handleRotationsChanged = (rotations) => {
  hasRotations.value = rotations.length > 0
  currentRotations.value = rotations
  console.log('旋转状态变化:', rotations)
}

const addAuthor = () => {
  ruleForm.authorInfo.push({
    rank: '',
    name: '',
    identity: '',
    institution: ''
  })
}

const removeAuthor = (index) => {
  ruleForm.authorInfo.splice(index, 1)
}

const submit = async () => {
  try {
    isSubmitting.value = true
    ruleFormRef.value.validate(async (valid) => {
      if (valid) {
        // 如果有旋转，先保存旋转
        if (hasRotations.value && currentRotations.value.length > 0 && ruleForm.pdfPath) {
          try {
            // 组装批量更新请求数据
            const batchData = {
              filePath: ruleForm.pdfPath, // PDF文件路径
              pages: currentRotations.value.map(rotation => ({
                pageNumber: rotation.pageIndex + 1, // 页码从1开始
                rotation: rotation.rotation // 旋转角度
              }))
            }

            console.log('批量更新旋转请求数据:', batchData)

            const rotationResult = await batchUpdatePdfPages(batchData)
            console.log('批量更新旋转结果:', rotationResult)

            if (rotationResult.code !== "0") {
              ElMessage.error('保存旋转失败: ' + (rotationResult.message || '未知错误'))
              return
            }



            // 重置旋转状态
            hasRotations.value = false
            currentRotations.value = []

            // 通知PDF预览组件重新加载
            if (pdfPreviewRef.value && pdfPreviewRef.value.reloadPDF) {
              await pdfPreviewRef.value.reloadPDF(ruleForm.pdfPath)
            }

          } catch (rotationError) {
            console.error('保存旋转失败:', rotationError)
            ElMessage.error('保存旋转失败: ' + (rotationError.message || '网络错误'))
            return
          }
        }

        const formData = {
          ...ruleForm,
          authorizationDate: formatDate(ruleForm.authorizationDate),
          applicationDate: formatDate(ruleForm.applicationDate)
        };

        savePatent(formData)
            .then(res => {
              if (res.code === 1) {
                ElMessage.success('上传成功');
                router.push("/main/result/patent");
              } else {
                ElMessage.error('上传失败');
              }
            })
            .catch(error => {
              console.error('请求错误:', error);
              ElMessage.error('请求失败，请重试');
            });
      } else {
        ElMessage.error('请填写必填项');
        return false;
      }
    });
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败，请重试')
  } finally {
    isSubmitting.value = false
  }
};

// 组件挂载时获取课题列表
onMounted(async () => {
  try {
    const response = await getCompletedLongitudinal();
    if (response.code === 1 && Array.isArray(response.data)) {
      longitudinalProjects.value = response.data;
    } else {
      ElMessage.error('获取结题的纵向课题失败');
    }
  } catch (error) {
    console.error('获取结题的纵向课题出错:', error);
    ElMessage.error('获取结题的纵向课题失败，请刷新页面重试');
  }
});

</script>

<style scoped>
.upload-button {
  height: 5vh;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 1rem;
  cursor: pointer;
}

.upload-button:hover:not(:disabled) {
  background-color: #45a049;
}

.upload-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}
</style>
